//后台接口
'use strict'

const Controller =  require('egg').Controller

class IndexController extends Controller{
    async checkLoginController(){
        const ctx = this.ctx
        let result = await ctx.service.admin.checkLoginService(ctx.request.body)
        // console.log(ctx.cookies.ctx.request.header.cookie)
        // console.log(ctx.session.EGG_SESS)
        // console.log(ctx.session)
        // console.log(ctx.session.openId)
        if (result.length > 0) {
            let openId = Date.now()
            ctx.session.openId = {'openId':openId}
            // console.log(ctx.session.openId)
            ctx.body ={'data':'登录成功','openId':openId}
        }else{
            ctx.body ={'data':'登录失败'}
        }
        
    }
    async getTypeInfoController(){
        const ctx = this.ctx
        let result = await ctx.service.admin.getTypeInfoService()
        ctx.body={
            data:result
        }
    }

    //添加文章
    async addArticleController(){
        const {ctx} = this
        // console.log(ctx.request.body)
        let result = await ctx.service.admin.addArticleService(ctx.request.body)

         //数据库改变了一行就表示插入成功
        const insertSuccess = result.affectedRows  === 1
        const insertId = result.insertId
        ctx.body ={
            status:insertSuccess,
            data:{
                id:insertId
            }
        }
    }

    //修改文章
    async updateArticleController(){
        const {ctx} = this
        let result = await ctx.service.admin.updateActicleService(ctx.request.body)

        //查看数据库是否更新一行
        const updateSuccess = result.affectedRows  === 1

        ctx.body={
            status:updateSuccess
        }
    }
    
    //获得文章列表
    async getArticleListController(){
        const {ctx} = this
        let resulet = await ctx.service.admin.getArticleListService()

        //查看到数据库传来的数据 传给前端
        ctx.body ={
            data:resulet
        }
        
    }

    //删除文章
    async delArticleController(){
        const {ctx} = this
        let result = await ctx.service.admin.delArticleService(ctx.params.id)
         //查看数据库是否更新一行
         const deleteSuccess = result.affectedRows  === 1

        ctx.body={
            status:deleteSuccess
        }
    }

    //修改文章
    async editArticleController(){
        const {ctx} = this
        let result = await ctx.service.admin.editArticleService(ctx.params.id)
      
        ctx.body={
            status:result.length > 0 ? true : false,
            data:result
        }
        
    }
    
}

module.exports = IndexController;